import { notification } from 'ant-design-vue'
import axios from 'axios'
import { token } from './token'

const request = axios.create({
  baseURL: process.env.NODE_ENV == 'development' ? 'http://localhost:3000' : ''
})

request.interceptors.request.use((config) => {
  config.headers = config.headers || {}
  if (!config.headers['Authorization']) {
    config.headers['Authorization'] = token.get()
  }
  return config
})

request.interceptors.response.use(res => {
  return Promise.resolve(res)
}, error => {
  if (error.response) {
    let { status, data = {} } = error.response
    let { message } = data
    if (status == 500) {
      notification.error({ message: '系统提示', description: message || '系统错误，请稍后再试' })
    } else if (status == 401) {
      notification.error({ message: '未授权', description: message || '未登录或账号没有权限', onClose: () => window.location.reload() })
    } else if (status == 400) {
      notification.error({ message: '系统提示', description: message || '请求参数有误，请修改后再试。' })
    }
  } else {
    notification.error({ message: '系统提示', description: error.message || '系统错误，请稍后再试' })
  }
  return Promise.reject(error)
})

export { request }